//规则, 组件名字驼峰, 元素标签中划线分割, 两者映射缺一不可.
angular.module("app").component("winitBasicsNeed", {
  templateUrl: getTemplateUrl("matrix/component/tpl/winitBasicsNeed.html"),
  bindings: {
    blur: "&",
    need: "<",
    userList: "<",
    showBtn: "<",
      basicReadOnly:"<"
  },
  controller: function(
    $http,
    $scope,
    $rootScope,
    $stateParams,
    $element,
    $attrs,
    $timeout,
    lodash
  ) {
      var ctrl = this;
      ctrl.info = { objectives: null, sources: null, brdTypes: null, basic: true, customer: {}, selCustomer: {}, selDepartment: {} }; // 需求目的 // 需求来源 // 需求类型
      ctrl.need.createTime = ctrl.need.createTime || Date.parse(new Date());
      ctrl.pdRole = false;
      // 设置提出人和跟进人是默认当前用户
      if(!ctrl.need.sltCreator){
          ctrl.need.sltCreator = { crtname: getUserName(), realname: getUserName(), account: getUserAccount() };
      }

      //判断是否时当前用户
      $scope.isSameOne = false;
      $scope.currentAccount =getUserAccount();
      $scope.isSame=function() {
          if ($scope.currentAccount == ctrl.need.proposerAccount)
              $scope.isSameOne = true
          else
              $scope.isSameOne= false
      }




      $scope.fetchCustomers=function () {
          if(ctrl.need.source=="CUSTOMER"){
              getCustomers()
          }
      }

      ctrl.$onChanges = function() {
          setAppointAccept(ctrl.need);
          getDataType(ctrl.showBtn);
          $scope.isSame();
          $scope.fetchCustomers();
      };
      $scope.isAdmin = $rootScope.isUserCanOperateByRole();
      // 获取数据类型（需求来源，需求类型，需求目的）
      function getDataType(showBtn) {
        if ($stateParams.type) {
          angular.forEach(config_need_objectives, function(obj) {
            obj.check = false;
          });
        }
        ctrl.info.objectives = config_need_objectives;
        angular.forEach(ctrl.info.objectives, function(obj) {
          var otherS = lodash.findWhere(ctrl.need.purpose, obj.key);
          if (otherS) {
            obj.check = true;
            if (obj.key == 6) {
              ctrl.need.showObjItem = true;
            }
          }
          if (showBtn && obj.value == "降低成本") {
            obj.check = true;
          }
        });
      }

      // 来源数据（需求来源）
      ctrl.info.sources = config_need_sources;
      angular.forEach(ctrl.info.sources, function(source) {
        source.crtname = source.value;
        if (ctrl.need.source == source.key) {
          ctrl.need.sourceObj = source;
        }
      });

      // 保存选中的需求目数据 选择目的后促发相应动作
      $scope.selecObjective = function(obj) {
        ctrl.need.sltObj = [];
        obj.check = !obj.check;
        angular.forEach(ctrl.info.objectives, function(objective) {
          if (objective.check) {
            ctrl.need.sltObj.push(objective);
          }
        });

        if (ctrl.need.sltObj.length == 0) {
          ctrl.need.lossPrevent.isChecked = false;
          ctrl.need.saveCost.isChecked = false;
          ctrl.need.expectLowerCostList = "";
        } else {
          ctrl.need.sltObj.forEach(function(objective) {
            if (objective.key == "3" || objective.key == "2") {
              ctrl.need.lossPrevent.isChecked = true;
              ctrl.need.saveCost.isChecked = true;
              ctrl.need.expectLowerCostList = [{}];
            } else {
              ctrl.need.lossPrevent.isChecked = false;
              ctrl.need.saveCost.isChecked = false;
              ctrl.need.expectLowerCostList = "";
            }
          });
        }
        ctrl.otherS = lodash.findWhere(ctrl.need.sltObj, { value: "其他" });
        if (ctrl.otherS) {
          ctrl.need.showObjItem = true;
        } else {
          ctrl.need.showObjItem = false;
          ctrl.need.sltItemValue = "";
        }
      };

      // 设置默认指定受理人
      function setAppointAccept(need) {
        var acceptItem = lodash.findWhere(ctrl.userList, {
          account: need.appointAcceptAccount
        });
        ctrl.need.sltAappointAcceptAccount = acceptItem || "";
      }

      // 设置指定受理人
      $scope.selectAappointAcceptItem = function(item) {
        ctrl.need.appointAcceptAccount = item.account || "";
        ctrl.need.appointAcceptName = item.realname || "";
      };

      $scope.selectSource = function(item) {
        console.log("source=====" + JSON.stringify(item));
        var sourceType = item.key;
        if (item.key == "CUSTOMER") {
          customerShow();
        } else if (sourceType == "DEPARTMENTS") {
          departmentsShow();
        } else {
          workOrederShow();
        }
      };

      $scope.selectCustomer = function(item) {
        ctrl.need.customers.selCustomer = item;
        var customerType = item.type;
        if (customerType == "super") {
          ctrl.info.customer.type = "super";
        } else {
          ctrl.info.customer.type = "general";
        }
      };

      $scope.selectDepartment = function(item) {
        console.log("department----" + JSON.stringify(item));
        ctrl.need.departments.selDepartment = item;
      };

      //转成编辑模式
      $scope.change2Edit=function (value) {
          ctrl.basicReadOnly=false
          $scope.basicEditable=true
      }

      //转成只读模式
      $scope.change2Read=function (value) {
          ctrl.basicReadOnly=true
          $scope.basicReadOnly=true
      }


      function customerShow() {
        ctrl.need.customers={show: true};
        ctrl.need.departments={show: false};
        ctrl.need.workOrder={show: false};
        getCustomers()
      }
      function departmentsShow() {
          ctrl.need.customers={show: false};
          ctrl.need.departments={show: true};
          ctrl.need.workOrder={show: false};
        ctrl.need.departments.datas = config_need_departments;
      }
      function workOrederShow() {
          ctrl.need.customers={show: false};
          ctrl.need.departments={show: false};
          ctrl.need.workOrder={show: true,
              ticketNumber:"",
              content:ticketed_url};

      }

      //获取客户资源
      function getCustomers() {
        var url = matrix_product_url+ "/needcustomer/getCustomers";
        $http({
          method: "get",
          url: url,
          headers: { "Content-Type": "application/json" }
        }).success(function(result) {
          var customers = [];
          customers = result.data;
            ctrl.need.customers.datas=[]
          if (customers && customers.length > 0) {
            customers.forEach(function(a) {
              if (a.type == "customer") {
                ctrl.need.customers.datas.push({
                  crtname: a.code + " " + a.name,
                    key:a.id
                });
              }
            });
          } else {
            $rootScope.toasterErrorInfo("获取客户资源失败");
            return false;
          }
        });
      }

      $scope.isDisabled = false;
      $scope.basicEdit = function () {
          $scope.isDisabled = true;
          ctrl.basicReadOnly=false
          $timeout(function () {
              $scope.isDisabled = false;
          },1000)
      }
    }
});
